<?php
/**
 * @package orinoco.framework
 * @subpackage database
 * @author Ryan Yonzon <rawswift@gmail.com>
 * @copyright Copyright 2008 Ryan Yonzon 
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

require('adapter.interface.php');

/**
 * MySQL implementation
 */
class mysql implements databaseAdapter {

	private $_db_resource;

	// constructor
	public function __construct($_host, $_username, $_password, $_database_name) {
		// establish db connection
		$this->_db_resource = mysql_connect($_host, $_username, $_password);
			if(!$this->_db_resource) {
				return false;
			}
		// select database
		mysql_select_db($_database_name, $this->_db_resource);
		return true;
	}
	
	// direct SQL query
	public function rawQuery($_sql_statement) {
		return mysql_query($_sql_statement, $this->_db_resource);		
	}
	
	// get field's type
	public function getFieldType($_model, $_variable_name) {
		$_result = mysql_query('SELECT * FROM ' . strtolower($_model) . ';', $this->_db_resource);
		$_field_num = mysql_num_fields($_result);
		for($_i = 0; $_i < $_field_num; $_i++) {
			if(mysql_field_name($_result, $_i) == $_variable_name) {
				return mysql_field_type($_result, $_i);
			}
		}
		return false;
	}
	
	// get field's flag
	public function getFieldFlags($_model, $_variable_name) {
		$_result = mysql_query('SELECT * FROM ' . strtolower($_model) . ';', $this->_db_resource);
		$_field_num = mysql_num_fields($_result);
		for($_i = 0; $_i < $_field_num; $_i++) {
			if(mysql_field_name($_result, $_i) == $_variable_name) {
				return mysql_field_flags($_result, $_i);
			}
		}
		return false;
	}
	
	// get field's enum data
	public function getEnumData($_model, $_field_name) {
		$_cols = mysql_query('SHOW COLUMNS FROM ' . strtolower($_model) . ' WHERE Field = "' . $_field_name . '";');
		$_cols_row = mysql_fetch_object($_cols);

			// check if get anything
			if(!is_object($_cols_row)) {
				return false;
			}
		
		// remove data that is not needed
		$_raw_enum = preg_replace(array('(enum\()', '(\))', '(\')'), array('', '', ''), $_cols_row->Type);
		
		// return the enum data in array format
		return preg_split("/\,/", $_raw_enum, 0, PREG_SPLIT_NO_EMPTY);
	}

	// escape string wrapper
	public function escapeString($_str) {
		return mysql_real_escape_string($_str);
	}
	
	// fetch result as object
	public function fetchObject($_res) {
		return mysql_fetch_object($_res);
	}
	
	// set data pointer
	public function dataSeek($_res, $_pointer) {
		mysql_data_seek($_res, $_pointer);
	}
	
	// get number of data rows
	public function getNumRows($_res) {
		return mysql_num_rows($_res);
	}
	
	// self destruct
	public function __destruct() {
		unset($this);
	}
	
} // end class

// -EOF-